

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言如果要想成为一名中高级测试开发，能够实现定制化封装自动化框架，是必须要掌握的技能。 其中，封装自动化框架我们会分成两类：  关键字封装 面向对象封装  两种封装方式各有各的好处，其中关键字封装的难度会更高。 它要求框架设计者需要有丰富的编程经验，对代码模块、逻辑、规范等设计要具有易用性、拓展性、容错性。 下面，我就先对这关键字封装进行简单的讲解，自动化方向为接口自动化。 后面的内容会涉及很多y">
<meta property="og:type" content="article">
<meta property="og:title" content="自动化框架设计模式 -- 关键字驱动">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2022/09/25/autoTest/designModeKeyword/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言如果要想成为一名中高级测试开发，能够实现定制化封装自动化框架，是必须要掌握的技能。 其中，封装自动化框架我们会分成两类：  关键字封装 面向对象封装  两种封装方式各有各的好处，其中关键字封装的难度会更高。 它要求框架设计者需要有丰富的编程经验，对代码模块、逻辑、规范等设计要具有易用性、拓展性、容错性。 下面，我就先对这关键字封装进行简单的讲解，自动化方向为接口自动化。 后面的内容会涉及很多y">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-09-25T05:51:56.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.244Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="自动化测试">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="pytest">
<meta property="article:tag" content="关键字驱动">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>自动化框架设计模式 -- 关键字驱动 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="自动化框架设计模式 -- 关键字驱动"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-09-25 13:51" pubdate>
          2022年9月25日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.6k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">自动化框架设计模式 -- 关键字驱动</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>如果要想成为一名中高级测试开发，能够实现定制化封装自动化框架，是必须要掌握的技能。</p>
<p>其中，封装自动化框架我们会分成两类：</p>
<ul>
<li>关键字封装</li>
<li>面向对象封装</li>
</ul>
<p>两种封装方式各有各的好处，其中关键字封装的难度会<strong>更高</strong>。</p>
<p>它要求框架设计者需要有丰富的编程经验，对代码模块、逻辑、规范等设计要具有<em><strong>易用性、拓展性、容错性</strong></em>。</p>
<p>下面，我就先对这<strong>关键字封装</strong>进行简单的讲解，自动化方向为<strong>接口自动化</strong>。</p>
<p>后面的内容会涉及很多yaml配置，不熟悉yaml语法的先自行百度了解一下。</p>
<blockquote>
<p>注意：这篇文章，只是对设计模式以及具体的一些思路的讲解，可供参考。</p>
</blockquote>
<blockquote>
<p>并不代表说，看了这篇文章你就可以开发一个完整自动化框架，还需要大量的实践和思考哦~</p>
</blockquote>
<blockquote>
<p>一个完整的自动化框架，讲解加实践，都得起码一到两周的时间。</p>
</blockquote>
<blockquote>
<p>希望能对你有所启发，有疑问或建议，欢迎联系作者。联系方式可以在【测开笔记】中找到。</p>
</blockquote>
<blockquote>
<p>测开笔记：<a href="https://walker_kwu.gitee.io/my-blog/2022/09/08/notes/top/">https://walker_kwu.gitee.io/my-blog/2022/09/08/notes/top/</a></p>
</blockquote>
<h1 id="关键字封装"><a href="#关键字封装" class="headerlink" title="关键字封装"></a>关键字封装</h1><p>关键字封装的设计，可以参考RF（全程robotFrameWork，是一款图形化的自动化测试框架）。</p>
<p>其优点在于：</p>
<ul>
<li>通用性，使用者不需要编码经验也能够完成大部分场景的自动化测试</li>
<li>规范性，使用的文件格式、内容格式，都需要按照框架的定义标准</li>
</ul>
<p>缺点：</p>
<ul>
<li>需要开发者拥有一定的代码经验</li>
<li>需要使用者付出一定的熟悉成本</li>
</ul>
<p>核心要领：</p>
<ul>
<li>定义用例文件格式，通常在excel、yaml中进行选择，个人偏向于yaml</li>
<li>定义项目文件格式，通常在yaml、ini、toml中进行选择，个人偏向于yaml</li>
<li>定义接口文件格式，通常在yaml、ini、toml中进行选择，个人偏向于yaml</li>
<li>定制化报告，非必要<ul>
<li>如果框架基于pytest，可以集成报告插件</li>
<li>如果框架自己设计代码运行逻辑，需要通过html/js/css等知识，来进行报告模板的开发。</li>
</ul>
</li>
</ul>
<h2 id="项目配置"><a href="#项目配置" class="headerlink" title="项目配置"></a>项目配置</h2><p>根目录下新建<strong>config</strong>文件夹，存放配置文件</p>
<p>在<strong>config</strong>文件夹中，新建projectConfig.yaml，用来存放项目配置。</p>
<p>接下来设计配置项（仅供参考）：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">TestProject:</span>               <span class="hljs-comment"># 项目名称ug</span><br>    <span class="hljs-attr">apiConfig:</span>               <span class="hljs-comment"># 接口通用配置</span><br>        <span class="hljs-attr">url:</span> <span class="hljs-string">http://www.baidu.com</span>               <span class="hljs-comment"># 接口通用域名</span><br>        <span class="hljs-attr">header:</span>               <span class="hljs-comment"># 接口通用请求头</span><br>    <span class="hljs-attr">globalVar:</span>               <span class="hljs-comment"># 全局变量</span><br>        <span class="hljs-attr">cookies:</span> <span class="hljs-string">&#x27;QAAZSAD!@#ASDC&#x27;</span>  <br>    <span class="hljs-attr">execConfig:</span>               <span class="hljs-comment"># 执行配置</span><br>        <span class="hljs-attr">switch:</span> <span class="hljs-literal">true</span>               <span class="hljs-comment"># 执行开关</span><br></code></pre></td></tr></table></figure>

<p>实际项目，配置项要更多，比如：</p>
<ul>
<li>发送邮件</li>
<li>第三方机器人</li>
<li>用例运行控制</li>
<li>数据库配置</li>
</ul>
<h2 id="接口文件"><a href="#接口文件" class="headerlink" title="接口文件"></a>接口文件</h2><p>在根目录新建文件夹<strong>apiConfig</strong></p>
<p>在<strong>apiConfig</strong>文件夹中，根据项目名再新建接口配置文件夹</p>
<p>这里用的是上面说的 <code>TestProject</code> </p>
<p>新建接口文件 <strong>百度的不知道是什么的接口.yaml</strong></p>
<p>接下来设计接口配置字段（仅供参考）：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">remark:</span> <span class="hljs-string">不知道什么用的接口</span>                <span class="hljs-comment"># 备注</span><br><span class="hljs-attr">url:</span> <span class="hljs-string">/mcp/pc/pcsearch</span>                   <span class="hljs-comment"># 接口路径</span><br><span class="hljs-attr">header:</span>                                 <span class="hljs-comment"># 接口请求头</span><br>  <span class="hljs-attr">&#x27;Content-Type&#x27;:</span> <span class="hljs-string">&#x27;application/json&#x27;</span><br><span class="hljs-attr">params:</span> <br><span class="hljs-attr">params_type:</span> <span class="hljs-string">json</span>                       <span class="hljs-comment"># 参数类型</span><br><span class="hljs-attr">method:</span> <span class="hljs-string">post</span>                            <span class="hljs-comment"># 请求方式，可选get/post</span><br><span class="hljs-attr">status_code:</span> <span class="hljs-number">302</span>                        <span class="hljs-comment"># 预期状态码</span><br></code></pre></td></tr></table></figure>

<p>实际项目，配置项要更多，比如：</p>
<ul>
<li>预期结果对比</li>
</ul>
<h2 id="用例文件"><a href="#用例文件" class="headerlink" title="用例文件"></a>用例文件</h2><p>在根目录新建文件夹<strong>testCase</strong></p>
<p>在<strong>testCase</strong>文件夹中，根据项目名再新建项目用例文件夹</p>
<p>这里用的是上面说的 <code>TestProject</code> </p>
<p>新建用例文件 <strong>1随便调用一个百度接口.yaml</strong></p>
<p>接下来设计用例字段：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">remark:</span> <span class="hljs-string">获取登录接口返回的token，以备接下来的接口调用，自动化测试运行前必须调用，更新token</span><br><br><span class="hljs-attr">case:</span>  <span class="hljs-comment"># 用例运行数据</span><br>  <span class="hljs-bullet">-</span> <span class="hljs-attr">api:</span> <span class="hljs-string">百度的不知道是什么的接口</span>  <span class="hljs-comment"># 调用的接口配置</span><br>    <span class="hljs-attr">header:</span>   <span class="hljs-comment"># 特殊的请求头</span><br>    <span class="hljs-attr">params:</span>   <span class="hljs-comment"># 特殊的请求参数</span><br><br>  <span class="hljs-bullet">-</span> <span class="hljs-attr">api:</span> <span class="hljs-string">百度的不知道是什么的接口</span><br>    <span class="hljs-attr">header:</span><br>    <span class="hljs-attr">params:</span><br></code></pre></td></tr></table></figure>

<p>实际项目，配置项要更多，比如：</p>
<ul>
<li>字段值保存到全局变量</li>
<li>预期结果对比</li>
<li>用例等级</li>
</ul>
<h2 id="核心代码文件"><a href="#核心代码文件" class="headerlink" title="核心代码文件"></a>核心代码文件</h2><p>在根目录新建文件夹<strong>coreCode</strong></p>
<p>在<strong>coreCode</strong>文件夹中，根据代码业务逻辑区分，比如：接口请求封装、公用函数</p>
<h3 id="接口请求封装"><a href="#接口请求封装" class="headerlink" title="接口请求封装"></a>接口请求封装</h3><p>在<strong>coreCode</strong>文件夹中，新建<strong>newRequests.py</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><span class="hljs-keyword">import</span> requests<br><span class="hljs-keyword">import</span> copy<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">GetRequest</span>():<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, url, header, params, params_type, method</span>):<br>        self.url = url<br>        self.header = copy.deepcopy(header)<br>        self.params = copy.deepcopy(params)<br>        self.params_type = params_type<br>        self.method = method<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(self.params_type, <span class="hljs-built_in">str</span>):<br>            <span class="hljs-keyword">if</span> self.params_type.upper() == <span class="hljs-string">&#x27;JSON&#x27;</span>:<br>                self.params = json.dumps(self.params)<br>                <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(self.header, <span class="hljs-built_in">dict</span>):<br>                    self.header[<span class="hljs-string">&#x27;Content-Type&#x27;</span>] = <span class="hljs-string">&#x27;application/json&#x27;</span><br>                <span class="hljs-keyword">else</span>:<br>                    self.header = &#123;<br>                        <span class="hljs-string">&#x27;Content-Type&#x27;</span>: <span class="hljs-string">&#x27;application/json&#x27;</span><br>                    &#125;<br><br>        <span class="hljs-keyword">if</span> self.header == <span class="hljs-string">&#x27;None&#x27;</span> <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> self.header:<br>            self.header = &#123;&#125;<br><br>        <span class="hljs-keyword">if</span> self.params == <span class="hljs-string">&#x27;None&#x27;</span> <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> self.params:<br>            self.params = &#123;&#125;<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">request</span>(<span class="hljs-params">self</span>):<br>        method = self.method.upper()<br>        <span class="hljs-keyword">if</span> method == <span class="hljs-string">&#x27;GET&#x27;</span>: <span class="hljs-keyword">return</span> self.get()<br>        <span class="hljs-keyword">elif</span> method == <span class="hljs-string">&#x27;POST&#x27;</span>: <span class="hljs-keyword">return</span> self.post()<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">get</span>(<span class="hljs-params">self</span>):<br>        response = requests.get(<br>            url=self.url,<br>            headers=self.header,<br>            data=self.params,<br>            allow_redirects=<span class="hljs-literal">False</span>,<br>        )<br>        <span class="hljs-keyword">return</span> response<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">post</span>(<span class="hljs-params">self</span>):<br>        response = requests.post(<br>            url=self.url,<br>            headers=self.header,<br>            data=self.params,<br>            allow_redirects=<span class="hljs-literal">False</span><br>        )<br>        <span class="hljs-keyword">return</span> response<br></code></pre></td></tr></table></figure>

<h3 id="公用函数"><a href="#公用函数" class="headerlink" title="公用函数"></a>公用函数</h3><p>在<strong>coreCode</strong>文件夹中，新建<strong>pubilc.py</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os<br><span class="hljs-keyword">import</span> yaml<br><span class="hljs-keyword">import</span> re<br><span class="hljs-keyword">from</span> copy <span class="hljs-keyword">import</span> deepcopy<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_path</span>(<span class="hljs-params">path</span>):  <span class="hljs-comment"># 动态获取路径</span><br>    <span class="hljs-keyword">return</span> os.path.abspath(os.path.join(os.path.dirname(__file__), <span class="hljs-string">f&#x27;../<span class="hljs-subst">&#123;path&#125;</span>&#x27;</span>))<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_yaml</span>(<span class="hljs-params">path</span>):  <span class="hljs-comment"># 获取yaml文件的数据</span><br>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(path, <span class="hljs-string">&#x27;r&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>        data = yaml.load(f, Loader=yaml.FullLoader)<br>    <span class="hljs-keyword">return</span> data<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_library</span>(<span class="hljs-params">project</span>):  <span class="hljs-comment"># 获取接口配置库</span><br>    lib_path = get_path(<span class="hljs-string">f&#x27;apiConfig/<span class="hljs-subst">&#123;project&#125;</span>&#x27;</span>)<br>    libraries = os.listdir(lib_path)<br>    api_lib = &#123;&#125;<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_api</span>(<span class="hljs-params">path</span>):<br>        <span class="hljs-keyword">if</span> os.path.isfile(path) <span class="hljs-keyword">and</span> path.endswith(<span class="hljs-string">&#x27;.yaml&#x27;</span>):<br>            api_lib[path[:-<span class="hljs-number">5</span>].replace(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;lib_path&#125;</span>/&quot;</span>, <span class="hljs-string">&#x27;&#x27;</span>)] = get_yaml(path)<br>        <span class="hljs-keyword">elif</span> os.path.isdir(path):<br>            path_list = os.listdir(path)<br>            <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> path_list:<br>                abs_path = <span class="hljs-string">f&quot;<span class="hljs-subst">&#123;path&#125;</span>/<span class="hljs-subst">&#123;item&#125;</span>&quot;</span><br>                generate_api(abs_path)<br><br>    <span class="hljs-keyword">for</span> lib <span class="hljs-keyword">in</span> libraries:<br>        abs_path = <span class="hljs-string">f&quot;<span class="hljs-subst">&#123;lib_path&#125;</span>/<span class="hljs-subst">&#123;lib&#125;</span>&quot;</span><br>        generate_api(abs_path)<br><br>    <span class="hljs-keyword">return</span> api_lib<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_case_list</span>(<span class="hljs-params">case_path</span>):<br><br>    case_list = []<br>    find_case(<br>        case_path,<br>        case_list,<br>    )<br>    case_list.sort(key=<span class="hljs-keyword">lambda</span> x: <span class="hljs-built_in">int</span>(re.match(<span class="hljs-string">r&#x27;\d+&#x27;</span>, x[<span class="hljs-string">&#x27;case_name&#x27;</span>]).group(<span class="hljs-number">0</span>)))  <span class="hljs-comment"># 按照用例编号排序</span><br>    <span class="hljs-keyword">return</span> case_list<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">find_case</span>(<span class="hljs-params">path, case_list</span>):<br>    <span class="hljs-keyword">if</span> os.path.isfile(path):<br>        <span class="hljs-keyword">if</span> path.endswith(<span class="hljs-string">&#x27;.yaml&#x27;</span>):<br>            case_name = path.split(<span class="hljs-string">&#x27;/&#x27;</span>)[-<span class="hljs-number">1</span>].replace(<span class="hljs-string">&#x27;.yaml&#x27;</span>, <span class="hljs-string">&#x27;&#x27;</span>)<br>            case_data = get_yaml(path)<br>            case_list.append(&#123;<br>                <span class="hljs-string">&#x27;case_name&#x27;</span>: case_name,<br>                <span class="hljs-string">&#x27;case_data&#x27;</span>: case_data<br>            &#125;)<br>                        <br>    <span class="hljs-keyword">else</span>:<br>        path_list = os.listdir(path)<br>        <span class="hljs-keyword">for</span> child <span class="hljs-keyword">in</span> path_list:<br>            find_case(<br>                <span class="hljs-string">f&quot;<span class="hljs-subst">&#123;path&#125;</span>/<span class="hljs-subst">&#123;child&#125;</span>&quot;</span>,<br>                case_list<br>            )<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">combine</span>(<span class="hljs-params">api, case</span>):  <span class="hljs-comment"># 将用例中指定的接口配置，集成到用例步骤中</span><br>    combine_list = [<span class="hljs-string">&#x27;header&#x27;</span>, <span class="hljs-string">&#x27;params&#x27;</span>]<br>    <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> api.items():<br>        copy_api = deepcopy(v)<br>        <span class="hljs-keyword">if</span> k <span class="hljs-keyword">in</span> combine_list:<br>            <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(case[k], <span class="hljs-built_in">dict</span>) <span class="hljs-keyword">and</span> <span class="hljs-built_in">isinstance</span>(api[k], <span class="hljs-built_in">dict</span>):<br>                copy_api.update(case[k])<br>                case[k] = copy_api<br>            <span class="hljs-keyword">elif</span> case[k] == <span class="hljs-string">&#x27;None&#x27;</span> <span class="hljs-keyword">or</span> <span class="hljs-keyword">not</span> case[k]:<br>                case[k] = copy_api<br>        <span class="hljs-keyword">else</span>:<br>            case[k] = copy_api<br></code></pre></td></tr></table></figure>

<h3 id="日志配置"><a href="#日志配置" class="headerlink" title="日志配置"></a>日志配置</h3><p>在<strong>coreCode</strong>文件夹中，新建<strong>logger.py</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> logging<br><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime<br><span class="hljs-keyword">import</span> os<br><br><span class="hljs-keyword">from</span> coreCode.pubilc <span class="hljs-keyword">import</span> get_path<br><br><br>LOGGER_FMT = <span class="hljs-string">&#x27;[%(asctime)s] - [%(levelname)s] : %(message)s&#x27;</span><br>LOGGER_FMT_PROJECT = <span class="hljs-string">&#x27;[%(asctime)s] - [Project: &#123;project&#125;] - [%(levelname)s] : %(message)s&#x27;</span><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">Logger</span>():<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    根据项目名生成日志文件，生成文件名格式为project/YYMMDD.log</span><br><span class="hljs-string"></span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, project=<span class="hljs-string">&#x27;&#x27;</span></span>):<br>        self.project = project<br>        self.ch = logging.StreamHandler()<br>        self.level = logging.DEBUG<br><br>        self.logger = logging.getLogger(<span class="hljs-string">f&#x27;<span class="hljs-subst">&#123;project&#125;</span>_log&#x27;</span>)  <span class="hljs-comment"># 增加参数log_name，会实例化不同logger</span><br>        self.logger.setLevel(self.level)<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(get_path(<span class="hljs-string">f&#x27;logs/<span class="hljs-subst">&#123;project&#125;</span>&#x27;</span>)):<br>            os.mkdir(get_path(<span class="hljs-string">f&#x27;logs/<span class="hljs-subst">&#123;project&#125;</span>&#x27;</span>))<br><br>        self.fh = logging.FileHandler(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;get_path(<span class="hljs-string">f&#x27;logs/<span class="hljs-subst">&#123;project&#125;</span>&#x27;</span>)&#125;</span>/<span class="hljs-subst">&#123;datetime.now().strftime(<span class="hljs-string">&#x27;%Y%m%d&#x27;</span>)&#125;</span>.log&quot;</span>,<br>                                    encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>)<br><br>        formatter = logging.Formatter(LOGGER_FMT)<br>        self.fh.setFormatter(formatter)<br>        self.logger.addHandler(self.fh)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">self, message</span>):<br>        self.fontColor(<span class="hljs-string">&#x27;\033[0;34m%s\033[0m&#x27;</span>)<br>        self.logger.debug(message)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">info</span>(<span class="hljs-params">self, message</span>):<br>        self.fontColor(<span class="hljs-string">&#x27;\033[0;32m%s\033[0m&#x27;</span>)<br>        self.logger.info(message)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">warning</span>(<span class="hljs-params">self, message</span>):<br>        self.fontColor(<span class="hljs-string">&#x27;\033[0;37m%s\033[0m&#x27;</span>)<br>        self.logger.warning(message)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">error</span>(<span class="hljs-params">self, message</span>):<br>        self.fontColor(<span class="hljs-string">&#x27;\033[0;31m%s\033[0m&#x27;</span>)<br>        self.logger.error(message)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">fontColor</span>(<span class="hljs-params">self, color</span>):<br>        <span class="hljs-comment"># 不同的日志输出不同的颜色</span><br>        formatter = logging.Formatter(color % LOGGER_FMT_PROJECT.<span class="hljs-built_in">format</span>(project=self.project))<br>        self.ch.setFormatter(formatter)<br>        self.logger.addHandler(self.ch)<br></code></pre></td></tr></table></figure>

<h2 id="运行主文件"><a href="#运行主文件" class="headerlink" title="运行主文件"></a>运行主文件</h2><p>开始前，需要现在根目录新建<strong>logs</strong>文件夹，来存放日志</p>
<p>然后根目录新建运行主文件<strong>main.py</strong></p>
<p>现在的目录结构应该是：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-bullet">-</span> <span class="hljs-string">apiConfig</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">TestProject</span><br>        <span class="hljs-bullet">-</span> <span class="hljs-string">百度的不知道是什么的接口.yaml</span><br><span class="hljs-bullet">-</span> <span class="hljs-string">config</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">projectConfig.yaml</span><br><span class="hljs-bullet">-</span> <span class="hljs-string">coreCode</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">logger.py</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">newRequests.py</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">pubilc.py</span><br><span class="hljs-bullet">-</span> <span class="hljs-string">logs</span><br><span class="hljs-bullet">-</span> <span class="hljs-string">testCase</span><br>    <span class="hljs-bullet">-</span> <span class="hljs-string">TestProject</span><br>        <span class="hljs-bullet">-</span> <span class="hljs-number">1</span><span class="hljs-string">随便调用一个百度接口.yaml</span><br><span class="hljs-bullet">-</span> <span class="hljs-string">main.py</span><br></code></pre></td></tr></table></figure>

<p>main.py的内容：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> listdir<br><br><span class="hljs-keyword">from</span> coreCode.pubilc <span class="hljs-keyword">import</span> get_yaml, get_path, get_case_list, get_library, combine<br><span class="hljs-keyword">from</span> coreCode.logger <span class="hljs-keyword">import</span> Logger<br><span class="hljs-keyword">from</span> coreCode.newRequests <span class="hljs-keyword">import</span> GetRequest<br><br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">execMain</span>(<span class="hljs-params">config, libraries, case_list, logger</span>):<br>    logger.debug(<span class="hljs-string">&quot;执行数据总打，依次为：Config/libraries/case_list&quot;</span>)<br>    logger.debug(config)<br>    logger.debug(libraries)<br>    logger.debug(case_list)<br>    <br>    <span class="hljs-keyword">for</span> case_scene <span class="hljs-keyword">in</span> case_list:<br>        <span class="hljs-keyword">if</span> <span class="hljs-string">&#x27;case&#x27;</span> <span class="hljs-keyword">in</span> case_scene[<span class="hljs-string">&#x27;case_data&#x27;</span>].keys():<br>            <span class="hljs-keyword">for</span> case_idx, case <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(case_scene[<span class="hljs-string">&#x27;case_data&#x27;</span>][<span class="hljs-string">&#x27;case&#x27;</span>]):<br>                logger.debug(<span class="hljs-string">f&quot;当前执行的用例：<span class="hljs-subst">&#123;case&#125;</span>&quot;</span>)<br><br>                api_name = case[<span class="hljs-string">&#x27;api&#x27;</span>]<br>                <span class="hljs-keyword">if</span> api_name <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> libraries.keys():<br>                    logger.error(<span class="hljs-string">f&quot;调用的api &#x27;<span class="hljs-subst">&#123;api_name&#125;</span>&#x27; 不存在于接口库&quot;</span>)<br>                    <span class="hljs-keyword">continue</span><br><br>                combine(libraries[api_name], case)<br>                <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> (<span class="hljs-string">&#x27;https&#x27;</span> <span class="hljs-keyword">in</span> case[<span class="hljs-string">&#x27;url&#x27;</span>] <span class="hljs-keyword">or</span> <span class="hljs-string">&#x27;http&#x27;</span> <span class="hljs-keyword">in</span> case[<span class="hljs-string">&#x27;url&#x27;</span>]):<br>                        case[<span class="hljs-string">&#x27;url&#x27;</span>] = config[<span class="hljs-string">&#x27;apiConfig&#x27;</span>][<span class="hljs-string">&#x27;url&#x27;</span>] + case[<span class="hljs-string">&#x27;url&#x27;</span>]<br><br>                logger.debug(<span class="hljs-string">f&quot;集成接口配置后的用例：<span class="hljs-subst">&#123;case&#125;</span>&quot;</span>)<br><br>                request_obj = GetRequest(<br>                    url=case[<span class="hljs-string">&#x27;url&#x27;</span>],<br>                    header=case[<span class="hljs-string">&#x27;header&#x27;</span>],<br>                    params=case[<span class="hljs-string">&#x27;params&#x27;</span>],<br>                    params_type=case[<span class="hljs-string">&#x27;params_type&#x27;</span>],<br>                    method=case[<span class="hljs-string">&#x27;method&#x27;</span>],<br>                )<br><br>                response = request_obj.request()<br>                response.close()<br>                status_code = response.status_code<br><br>                <span class="hljs-keyword">if</span> case[<span class="hljs-string">&#x27;status_code&#x27;</span>] != status_code:<br>                    logger.error(<span class="hljs-string">f&quot;接口响应码 &#x27;<span class="hljs-subst">&#123;status_code&#125;</span>&#x27; 与接口设定值 <span class="hljs-subst">&#123;case[<span class="hljs-string">&#x27;status_code&#x27;</span>]&#125;</span> 不匹配&quot;</span>)<br>                    <span class="hljs-keyword">continue</span><br>                logger.debug(<span class="hljs-string">f&quot;接口返回数据：<span class="hljs-subst">&#123;response.text&#125;</span>&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    rootLogger = Logger(<span class="hljs-string">&#x27;root&#x27;</span>)<br>    project_list = listdir(get_path(<span class="hljs-string">&#x27;testCase&#x27;</span>))<br>    config_suite = get_yaml(get_path(<span class="hljs-string">&#x27;config/projectConfig.yaml&#x27;</span>))<br><br>    rootLogger.debug(<span class="hljs-string">f&quot;项目列表：<span class="hljs-subst">&#123;project_list&#125;</span>&quot;</span>)<br>    rootLogger.debug(<span class="hljs-string">f&quot;项目配置：<span class="hljs-subst">&#123;config_suite&#125;</span>&quot;</span>)<br><br>    <span class="hljs-keyword">for</span> project <span class="hljs-keyword">in</span> project_list:<br>        project_log = Logger(project=project)<br>        config = config_suite[project]<br><br>        <span class="hljs-keyword">if</span> config[<span class="hljs-string">&#x27;execConfig&#x27;</span>][<span class="hljs-string">&#x27;switch&#x27;</span>]:  <span class="hljs-comment"># 打开了开关才会运行</span><br>            libraries = get_library(project)<br>            case_list = get_case_list(get_path(<span class="hljs-string">f&quot;testCase/<span class="hljs-subst">&#123;project&#125;</span>&quot;</span>))<br><br>            project_log.debug(<span class="hljs-string">f&quot;接口配置库：<span class="hljs-subst">&#123;libraries&#125;</span>&quot;</span>)<br>            project_log.debug(<span class="hljs-string">f&quot;项目用例：<span class="hljs-subst">&#123;case_list&#125;</span>&quot;</span>)<br><br>            <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(case_list): <span class="hljs-comment"># 如果有用例</span><br>                execMain(<br>                    config,<br>                    libraries,<br>                    case_list,<br>                    project_log,<br>                )<br>            <span class="hljs-keyword">else</span>:<br>                project_log.error(<span class="hljs-string">&quot;该项目暂无用例&quot;</span>)<br></code></pre></td></tr></table></figure>

<h1 id="写在最后"><a href="#写在最后" class="headerlink" title="写在最后"></a>写在最后</h1><p>以上示例代码，作者已经进行调试且运行成功。</p>
<p>用到的第三方库：</p>
<ul>
<li>requests, 接口请求库。安装：pip install requests</li>
<li>pyyaml，读取yaml文件数据。安装：pip install pyyaml</li>
</ul>
<p>安装环境后，按照上述步骤，一步步创建文件，填充内容，就可以运行。</p>
<p>当然，这<strong>并不是具备完整功能</strong>的自动化关键字框架。</p>
<p>该篇文章只是提供了一些思路，及其可以运行的简单demo。</p>
<p>可以在完全理解思路和代码后，再来思考下一步的框架功能填充。比如：</p>
<ul>
<li>数据依赖</li>
<li>数据驱动</li>
<li>报告输出</li>
<li>用例运行控制</li>
<li>发送邮件</li>
<li>数据库查询</li>
</ul>
<p>如果你有想法，但是没有思路，欢迎咨询作者，联系方式可以在【测开笔记】中找到。</p>
<blockquote>
<p>测开笔记：<a href="https://walker_kwu.gitee.io/my-blog/2022/09/08/notes/top/">https://walker_kwu.gitee.io/my-blog/2022/09/08/notes/top/</a></p>
</blockquote>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/" class="category-chain-item">自动化测试</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%A1%86%E6%9E%B6/" class="category-chain-item">自动化框架</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/">#自动化测试</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/pytest/">#pytest</a>
      
        <a href="/my-blog/tags/%E5%85%B3%E9%94%AE%E5%AD%97%E9%A9%B1%E5%8A%A8/">#关键字驱动</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>自动化框架设计模式 -- 关键字驱动</div>
      <div>https://walker_kwu.gitee.io/my-blog/2022/09/25/autoTest/designModeKeyword/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年9月25日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2022/09/26/notes/js/commonFunction/" title="javascript常用函数">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">javascript常用函数</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2022/09/23/notes/js/function/" title="JavaScript函数">
                        <span class="hidden-mobile">JavaScript函数</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
